import * as c from "@/util/c";
import { log, info, warn, error } from "@/util/tio"

import React, { useEffect, useState } from 'react';
/**
 * root context
 * 注：一级属性是原子的，要替换就全部替换了
 */
const TioContext = React.createContext([{}, () => { }]);

const TioContextProvider = ({ children, ...rest }) => {
    const [tioContext, setTioContext] = useState({
        curr: null,//{ name: "tan", id: "4444", phone: "18677778888" },
        theme: c.DEFAULT_THEME,//'light', //当前主题 dark or light, default is light
        tws: null, //TioWebsocket
    });

    useEffect(() => {
        updateTioContext([tioContext, setTioContext], { theme: c.DEFAULT_THEME });
    }, [])

    return (
        <TioContext.Provider value={[tioContext, setTioContext]}>
            {children}
        </TioContext.Provider>
    );
};

export let tioContextListeners = {};

/**
 * 更新tioContext
 * @param props 
 * @returns 
 */
const updateTioContext = ([tioContext, setTioContext], props) => {
    setTioContext(oldState => ({ ...oldState, ...props }));

    for (const key in tioContextListeners) {
        if (Object.prototype.hasOwnProperty.call(tioContextListeners, key)) {
            const func = tioContextListeners[key];
            // log(key);
            func([tioContext, setTioContext], props);
        }
    }
    return tioContext;
};


const addTioContextListener = (key, func) => {
    if (tioContextListeners[key]) {
        log(`key [${key}] alreadly exist`)
        return
    }
    tioContextListeners[key] = func;
    log(tioContextListeners);
    return tioContextListeners;
}

export { TioContext, TioContextProvider, updateTioContext, addTioContextListener };
export default TioContext
